import type { RouteRecordRaw } from "vue-router";
import { constantRoutes, asyncRoutes } from "@/router/common"


// const modules = import.meta.glob("../../views/**/**.vue");


/**
 * Use meta.role to determine if the current user has permission
 *
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    // 角色【超级管理员】拥有所有权限，忽略校验
    if (roles.includes("admin")) {
      return true;
    }
    return roles.some((role) => {
      if (route.meta?.roles) {
        //@ts-ignore
        return route.meta.roles.includes(role);
      }
    });
  }
  return false;
};

/**
 * 递归过滤用户角色拥有的路由
 *
 * @param routes 自己定义的全部动态路由
 * @param userAuthList 用户角色菜单集合
 * @returns 返回用户有权限的动态路由
 */

const filterAsyncRoutes = (routes: any, userAuthList: string[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  userAuthList.forEach((userRoute: any) => {
    const tempRoute = { ...userRoute }
    routes.forEach((route: any) => {
      const selfRoute = { ...route }
      if (tempRoute.name == selfRoute.name) {
        if (tempRoute.children && selfRoute.children) {
          tempRoute.children = filterAsyncRoutes(selfRoute.children, tempRoute.children)
        }
        //获取按钮权限
        let authBtnList: string[] = [];
        if (tempRoute.children && tempRoute.children.length) {
          tempRoute.children.forEach((item: any) => {
            if (item.auth_type === 0) {
              authBtnList.push(item.name);
            }
          });
        }
        let obj: RouteRecordRaw = {
          name: selfRoute.name,
          path: selfRoute.path,
          children: tempRoute.children,
          component: selfRoute.component,
          meta: Object.assign({}, selfRoute.meta, { authBtnList: authBtnList }, { title: selfRoute.title || tempRoute.title }, { hidden: selfRoute.hidden || Boolean(!tempRoute.is_menu) })
        }
        if (selfRoute.redirect &&
          selfRoute.children &&
          selfRoute.children.length > 0
          && selfRoute.children[0].name) {
          //@ts-ignore
          obj['redirect'] = { name: selfRoute.children[0].name }
        }
        asyncRoutes.push(obj)
      }
    });
  })
  return asyncRoutes
}

export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([]);
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    //@ts-ignore
    routes.value = constantRoutes.concat(newRoutes);
  }

  /**
 * 生成动态路由
 *
 * @param menus 用户角色集合
 * @returns
 */

  function generateRoutes(menus: string[]) {
    return new Promise((resolve, reject) => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, menus)
      setRoutes(accessedRoutes);
      console.log('accessedRoutes', accessedRoutes)
      resolve(accessedRoutes);
    })
  }

  return { routes, setRoutes, generateRoutes }
})

